﻿using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Machinery.Cogs.Interfaces;
using Ninject.Web.Mvc;

namespace Machinery.Cogs
{
    /// <summary>
    /// A very simple service that provides the current path. 
    /// A test convenience service, used to replace the current path when doing tests.
    /// </summary>
    public class PathCog : Cog, IPathCog
    {
        /// <summary>
        /// Get the path of the web applicaton.
        /// </summary>
        /// <returns></returns>
        public string GetApplicatonRootDirectory()
        {
            return HttpContext.Current.Server.MapPath("~/");
        }

        /// <summary>
        /// This is a wrapper for UrlHelper.RouteUrl. 
        /// Exists for mocking purposes - UrlHelper 
        /// is almost impossible to mock.
        /// </summary>
        /// <param name="routeValues">The routevalues that you want to pass to RouteUrl.</param>
        /// <returns>An url.</returns>
        public string RouteUrl(object routeValues)
        {
            return GetUrlHelper().RouteUrl(routeValues);
        }

        public string RouteUrl(string routeName, object routeValues)
        {
            return GetUrlHelper().RouteUrl(routeName, routeValues);
        }

        private static UrlHelper GetUrlHelper()
        {
            var httpContext = new HttpContextWrapper(HttpContext.Current);
            var routeData = RouteTable.Routes.GetRouteData(httpContext);
            return new UrlHelper(new RequestContext(httpContext, routeData));
        }
    }
}
